// elio框架自动生成JS源码并部署静态资源
const os = require('os');
const path = require('path');
const fs = require('fs');
function getIPAdress() {
    var interfaces = os.networkInterfaces();
    for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                return alias.address;
            }
        }
    }
}

function copyDir(src, dist, callback) {
    fs.access(dist, function(err){
        if(err){
            // 目录不存在时创建目录
            fs.mkdirSync(dist);
        }
        _copy(null, src, dist);
    });

    function _copy(err, src, dist) {
        if(err){
            callback(err);
        } else {
            try {
                const paths = fs.readdirSync(src)
                paths.forEach(function(path) {
                    const _src = src + '/' +path;
                    const _dist = dist + '/' +path;
                    fs.stat(_src, function(err, stat) {
                        if(err){
                            callback(err);
                        } else {
                            // 判断是文件还是目录
                            if(stat.isFile()) {
                                fs.writeFileSync(_dist, fs.readFileSync(_src));
                            } else if(stat.isDirectory()) {
                                // 当是目录是，递归复制
                                copyDir(_src, _dist, callback)
                            }
                        }
                    })
                })
            } catch (err) {
                callback(err)
            }
        }
    }
}

// 生成build.js
const code = `// 通过elio框架自动生成
// 请勿修改本文件
'use strict';
// 开发环境的服务器
export const HOST_DEV = '${getIPAdress()}'
// 生产环境的服务器
export const HOST_PROD = 'et.zhumang.vip'
`
// 生成代码
export function deploy (host = 'et.zhumang.vip') {
    fs.writeFile(path.join(__dirname, 'build.js'), code.replace('et.zhumang.vip', host), err => null)
    const publicDir = path.join(process.cwd(), 'public')
    copyDir(path.join(__dirname, 'public'), publicDir)
}